package class01.test;

import java.util.Random;

public class Code03_InsertionSort {
    public static void insertionSort(int[] arr){
        if(arr == null || arr.length < 2){
            return;
        }

        for (int i = 1; i < arr.length; i++) {
            for (int j = i-1; j >=0 ; j--) {
                if(arr[j] < arr[j+1]){
                    swap(arr,j,j+1);
                }
            }
        }
    }

    private static void swap(int[] arr, int j, int i) {
        int temp = arr[j];
        arr[j] = arr[i];
        arr[i] = temp;
    }


    public static void main(String[] args) {
        int testTime = 5000000;
        int maxSize = 100;
        int maxValue = 100;
        boolean succeed = true;
        for (int i = 0; i < testTime; i++) {
            int[] arr1 = generationRandomArray(maxSize,maxValue);
            int[] arr2 = copyArray(arr1);
            if(!isEquale(arr1,arr2)){
                succeed = false;
                printArray(arr1);
                printArray(arr2);
                break;
            }
        }
        System.out.println(succeed?"good":"bad");
        int[] arr1 = generationRandomArray(maxSize,maxValue);
        printArray(arr1);
        insertionSort(arr1);
        printArray(arr1);
    }

    private static void printArray(int[] arr1) {
        if(arr1 == null){
            return;
        }
        for (int i = 0; i < arr1.length; i++) {
            System.out.print(arr1[i] + " ");
        }
        System.out.println();
    }

    private static boolean isEquale(int[] arr1, int[] arr2) {
        if((arr1 ==null && arr2 != null) || (arr1 != null && arr2 == null)){
            return false;
        }
        if(arr1.length != arr2.length){
            return false;
        }
        if(arr1==null && arr2 ==null){
            return true;
        }
        for (int i = 0; i < arr1.length; i++) {
            if(arr1[i] != arr2[i]){
                return false;
            }
        }
        return true;
    }

    private static int[] copyArray(int[] arr1) {
        if(arr1 == null){
            return arr1;
        }
        int[] res = new int[arr1.length];
        for (int i = 0; i < res.length; i++) {
            res[i] = arr1[i];
        }
        return res;
    }

    private static int[] generationRandomArray(int maxSize, int maxValue) {
        int[] arr = new int[(int)((maxSize + 1)* Math.random())];
        for (int i = 0; i < arr.length; i++) {
            arr[i] = ((int)((maxValue + 1)*Math.random())) - ((int)((maxValue)*Math.random()));
        }
        return arr;
    }
}
